package com.atguigu.tingshu.account.service.impl;

import com.atguigu.tingshu.account.mapper.UserAccountDetailMapper;
import com.atguigu.tingshu.account.mapper.UserAccountMapper;
import com.atguigu.tingshu.account.receiver.AccountReceiver;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.model.account.UserAccount;
import com.atguigu.tingshu.model.account.UserAccountDetail;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Map;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {

	@Autowired
	private UserAccountMapper userAccountMapper;

	@Autowired
	private UserAccountDetailMapper userAccountDetailMapper;


	/**
	 * 添加账户信息
	 * @param userId
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public void addUserAccount(Long userId) {
		UserAccount userAccount = new UserAccount();
		userAccount.setUserId(userId);

		userAccount.setTotalAmount(new BigDecimal("100"));
		userAccount.setAvailableAmount(new BigDecimal("100"));
		userAccount.setTotalIncomeAmount(new BigDecimal("100"));

		userAccountMapper.insert(userAccount);

		// 新增账户变动历史
		if (userAccount.getAvailableAmount().intValue() > 0){
			this.saveUserAccountDetail(userId,"赠送", SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT,
					userAccount.getAvailableAmount(),null);
		}
	}

	/**
	 * 新增账户变动日志
	 * @param userId 用户ID
	 * @param title 资金变动缘由
	 * @param tradeType 交易类型
	 * @param amount 变动金额
	 * @param orderNo 订单编号
	 */
	@Override
	public void saveUserAccountDetail(Long userId, String title, String tradeType, BigDecimal amount, String orderNo) {
		UserAccountDetail userAccountDetail = new UserAccountDetail();

		userAccountDetail.setUserId(userId);
		userAccountDetail.setTitle(title);
		userAccountDetail.setTradeType(tradeType);

		userAccountDetail.setAmount(amount);
		userAccountDetail.setOrderNo(orderNo);

		userAccountDetailMapper.insert(userAccountDetail);
	}
}
